package csu.web.jpetstore.web.servlet;

import csu.web.jpetstore.domain.Product;
import csu.web.jpetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductsServlet extends HttpServlet {

    private static final String SEAECH_PRODUCTS_FORM = "/WEB-INF/jsp/catalog/searchProducts.jsp";
    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String MAIN_FORM = "/WEB-INF/jsp/catalog/main.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CatalogService catalogService = new CatalogService();
        HttpSession session = req.getSession();
        String keyword = req.getParameter("keyword");

        if (keyword.isEmpty()){
            req.getRequestDispatcher(MAIN_FORM).forward(req,resp);
        }

        List<Product> ProductList = catalogService.searchProductList(keyword);
        session.setAttribute("productList",ProductList);

        if (ProductList.size()==0){
            session.setAttribute("errorMsg","无此商品");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        }
        req.getRequestDispatcher(SEAECH_PRODUCTS_FORM).forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
